import {useState,useEffect,useRef} from 'react'
import './login.css'
import { Button, Input, Toast,Dialog,Form    } from 'react-vant'
import {useNavigate} from 'react-router-dom'
// import axios from 'axios'
import { api } from '../../luyou/index'
import { Mask } from 'antd-mobile'
import SliderCaptcha from 'rc-slider-captcha'; // 导入滑动验证码组件
import { sleep } from 'ut2'; // 导入sleep函数
import createPuzzle from 'create-puzzle'; // 导入createPuzzle函数
import { RubyOutlined, MehOutlined, SmileOutlined, RedoOutlined, LoadingOutlined } from '@ant-design/icons' // 导入Ant Design图标
export default function Login() {
  const naviate = useNavigate()
  let [tel,settel]=useState('')
  let [password,setpassword]=useState('')
  let [flag,setflag]=useState(false)
  let [flag2,setflag2]=useState(false)
  let [flag3,setflag3]=useState(false)
  let [flag4,setflag4]=useState(false)
  let [isShow,setisShow]=useState(false)
  const [imageData, setImageData] = useState(null);
  const [stream, setStream] = useState(null);
  const [visible, setVisible] = useState(false);
  const videoRef = useRef(null);
  const offsetXRef = useRef(0); // x 轴偏移值
  const [isSuccess, setIsSuccess] = useState(false); // 是否验证成功
  //手机号验证
  let telyan = () => {
    if(tel.length===0){
       setflag(true)
    }else{
       if(tel.length===11){
          setflag2(false)
       }else{
          setflag2(true)
       }
       setflag(false)
    }
  }
  //密码验证
  let mmyan = () => {
    if(password.length===0){
       setflag3(true)
    }else{
       if(password.length>=6&&password.length<=12){
          setflag4(false)
       }else{
          setflag4(true)
       }
       setflag3(false)
  }
 }
  //登录
  let denglu = async() => {
      let {data}=await api.post('/login',{phone:tel,password:password})
      console.log(data)
      if(data.code===200){
        sessionStorage.setItem('token',data.token)
        sessionStorage.setItem('user',JSON.stringify(data.data))
        Toast.success('登录成功')
        naviate('/home')
      }else{
        Toast.fail('登录失败')
      }
  }
    const showModal = () => {
        setisShow(true);
        She();
    };

    const closeModal = () => {
        handleLogin()
        setVisible(false);
    };
    // 初始化摄像头
    const She = async () => {
        // 检查浏览器是否支持 getUserMedia 以获取摄像头权限
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            await navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
                // 在此处处理视频流，例如获取帧数据
                if (videoRef.current) {
                    setStream(stream)
                    videoRef.current.srcObject = stream;
                }
            })
                .catch((err) => {
                    console.error('无法获取摄像头权限:', err);
                });
        } else {
            console.error('浏览器不支持 getUserMedia');

        }
    };
    useEffect(() => {
        if (stream) {
            setTimeout(() => {
                captureImage()
            }, 500)
        }
    }, [stream])
    const captureImage = () => {
        if (videoRef.current) {
            const canvas = document.createElement('canvas');
            canvas.width = videoRef.current.videoWidth;
            canvas.height = videoRef.current.videoHeight;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
            const dataUrl = canvas.toDataURL('image/jpeg');
            setImageData(dataUrl);

        } else {
            console.error('视频元素尚未初始化');
        }
    };
    const handleLogin = async () => {
        if (imageData) {
            // 在此处将 imageData 转换为 base64 格式并发送到后端进行人脸识别处理
            const b64 = 'data:image/jpeg;base64,' + imageData.split(',')[1];

            // 根据后端返回的结果进行处理
            Toast.loading({
                message: '加载中...',
                forbidClick: true,
            })
            let { data } = await api.post('/rllogin', { b64 })
            if (data.code === 200) {
                Toast.success('登录成功')
                stream.getTracks().forEach(track => track.stop())
                videoRef.current.srcObject = null;
                setImageData(null);
                sessionStorage.setItem('token', data.token)
                naviate('/home')
            } else {
                Toast.fail('人脸库无此人，请录入人脸')
            }
        }
    }
    const verifyCaptcha = async (data) => {
      await sleep();
      if (data.x >= offsetXRef.current - 5 && data.x < offsetXRef.current + 5) {
          denglu()
          setisShow(false)
          naviate('/home')
          return Promise.resolve();
      }
      alert('验证失败')
      return Promise.reject();
  };
  return (
    <div>
      <div style={{width:'6rem',margin:'0 auto',marginTop:'1.5rem'}}>
            <div className='L_img_box'>
                <img src="/public/02.jpeg" style={{width:'100%',height:'100%',borderRadius:'50%'}} alt="" />
            </div>
            <h1 style={{textAlign:'center'}}>速订魔方</h1>
      </div>
      <div className='L_box'>
        <div style={{marginBottom:'0.2rem'}}>
        <Input
            value={tel}
            type='tel'
            onChange={tel => {settel(tel)}}
            placeholder='请输入手机号'
            onBlur={telyan}
           
          />
          <span className={flag?'xian':'xiao'}>请输入手机号</span>
          <span className={flag2?'xian':'xiao'}>请输入正确的手机号</span>
        </div>
        <div >
          <Input
          value={password}
          type='password'
          onChange={password => {setpassword(password)}}
          placeholder='请输入密码'
          onBlur={mmyan}
        />
        <span className={flag3?'xian':'xiao'}>请输入密码</span>
        <span className={flag4?'xian':'xiao'}>请输入正确的密码</span>
        </div>
        <p style={{textAlign:'center',marginTop:'0.1rem'}}>
          <Button onClick={()=>{setIsSuccess(true)}} style={{color:'white',backgroundColor:'#ff2630',width:'3rem',height:'0.6rem',borderRadius:'0.5rem'}}><h2>登录</h2></Button><br />
          
        </p>
        <span style={{fontSize:'0.3rem'}} onClick={()=>{showModal()}}>人脸识别登录</span>
      </div>
      <div style={{width:'3rem',height:'0.5rem',display:'flex',justifyContent:'space-between',position:'relative',top:'20em',left:'2.18rem',marginTop:'0.7rem'}}>
        <p style={{fontSize:'0.3rem'}} onClick={()=>naviate('/zhuce')}>立即注册</p>
        <p style={{fontSize:'0.3rem'}} onClick={()=>naviate('/updatepass')}>忘记密码</p>
      </div>
      < Dialog
                visible={isShow}
                onClick={closeModal}
                title="人脸识别"
            >
                <div className='face-recognition-container' style={{ width: '2.8rem', height: '2.2rem', margin: '0.1rem auto', position: 'relative' }}>

                    <video ref={videoRef} autoPlay id='videos' playsInline muted style={{ width: '100%', height: '100%' }}></video>
                    <p>请将人脸对准摄像头</p>
                </div>
                <div>
                    <canvas></canvas>
                </div>
      </ Dialog >
     
        <Form >
            <Mask visible={isSuccess} onMaskClick={() => setIsSuccess(false)}>
                <div className='L_box2'>
                    <SliderCaptcha
                        request={() =>
                            createPuzzle('/public/01.jpg', {
                                format: 'blob'
                            }).then((res) => {

                                offsetXRef.current = res.x
                                return {
                                    // 背景图片
                                    bgUrl: res.bgUrl,
                                    // 核验区域
                                    puzzleUrl: res.puzzleUrl
                                };
                            })
                        }
                        onVerify={(data) => {
                            return verifyCaptcha(data);
                        }}
                        //bgSize必须和原图片的尺寸一样
                        bgSize={{ width: 335, height: 188 }}
                        tipIcon={{
                            default: <RubyOutlined />,
                            loading: <LoadingOutlined />,
                            success: <SmileOutlined />,
                            error: <MehOutlined />,
                            refresh: <RedoOutlined />
                        }}
                        tipText={{
                            default: '向右👉拖动完成拼图',
                            loading: '👩🏻‍💻🧑‍💻努力中...',
                            moving: '向右拖动至拼图位置',
                            verifying: '验证中...',
                            error: '验证失败'
                        }}
                    />
                </div>
            </Mask>
        </Form>
    </div>
  )
}
